package com.karolak.web.saf.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.karolak.service.Service;
import com.karolak.web.saf.action.ModelAction;
import com.opensymphony.xwork2.Action;

public class SaveCommand implements ActionCommand {

	protected Log log = LogFactory.getLog(getClass().getName());

	public <T, Id, S extends Service<T, Id>> void prepare(ModelAction<T, Id, S> action) {

	}

	public <T, Id, S extends Service<T, Id>> void validate(ModelAction<T, Id, S> action) {
		if (action.getModelId() == null) {
			return;
		}
		T entity = action.getService().findById(action.getModelId());
		if (entity == null) {
			return;
		}
		String msg = action.getText("unique.property.exists", new String[] { action.getText("id"), "" + action.getModelId() });
		action.addFieldError("entity.id", msg);
		if (log.isWarnEnabled()) {
			log.warn(msg);
		}
	}

	public <T, Id, S extends Service<T, Id>> String execute(ModelAction<T, Id, S> action) {
		T entity = action.getService().create(action.getModel());
		action.setModel(entity);
		if (log.isTraceEnabled()) {
			log.trace("Entity created:" + entity);
		}
		return Action.SUCCESS;
	}
}
